<template>
    <div class="register">
        <!-- <el-form>
            <el-form-item>
                <el-input></el-input>
            </el-form-item>
        </el-form> -->

        <!-- 点击提交自动校验 -->
        <!-- <van-form ref="regForm" class="regForm" @submit="onSubmit">
            <van-cell-group inset>
                <van-field v-model="RegParams.tel" name="tel" label="手机号" placeholder="手机号"
                    :rules="LoginRules.tel">
                </van-field>
                <van-field v-model="RegParams.password" :type="passwordShow ? 'text' : 'password'" name="password" label="密码"
                    placeholder="密码" :right-icon="passwordShow ? 'eye-o' : 'closed-eye'" @click-right-icon="onClickIcon"
                    :rules="LoginRules.password">
                </van-field>
                <van-field v-model="CodeParams.telcode" center clearable label="短信验证码"  placeholder="请输入短信验证码" :rules="LoginRules.telcode" :disabled="!isTelOk">
                    <template #button>
                        <van-button size="small" type="primary" @click="sendCode">发送验证码</van-button>
                    </template>
                </van-field>
            </van-cell-group>
            <div style="margin: 16px;">
                <van-button round block type="primary" native-type="submit">
                    提交
                </van-button>
            </div>
        </van-form> -->

        <!-- 选择手动提交 -->
        <van-form ref="regForm" class="regForm">
            <van-cell-group inset>
                <van-field v-model="RegParams.tel" name="tel" label="手机号" placeholder="手机号"
                    :rules="LoginRules.tel">
                </van-field>
                <van-field v-model="RegParams.password" :type="passwordShow ? 'text' : 'password'" name="password" label="密码"
                    placeholder="密码" :right-icon="passwordShow ? 'eye-o' : 'closed-eye'" @click-right-icon="onClickIcon"
                    :rules="LoginRules.password">
                </van-field>
                <van-field v-model="CodeParams.telcode" center clearable label="短信验证码"  placeholder="请输入短信验证码" :rules="LoginRules.telcode" :disabled="!isTelOk">
                    <template #button>
                        <van-button size="small" type="primary" @click="sendCode">发送验证码</van-button>
                    </template>
                </van-field>
            </van-cell-group>
            <div style="margin: 16px;">
                <van-button round block type="primary" @click="onSubmit">
                    提交
                </van-button>
            </div>
        </van-form>



       
    </div>
</template>

<script setup lang="ts">
// import type { Ref } from 'vue';
import { reactive, ref, toRef ,getCurrentInstance} from 'vue';
import { useRoute,useRouter } from 'vue-router';
import {reg} from "@/utils/rules"
import { doCheckPhoneAPI,doSendMsgCodeAPI,doCheckCodeAPI,doFinishRegisterAPI} from "@/api/user"
import { showSuccessToast,showFailToast } from 'vant';


/* const curr = getCurrentInstance();
const route = curr?.appContext.config.globalProperties.$route;
const router = curr?.appContext.config.globalProperties.$router;
console.log(1111,curr);

function useRoute(){
    const curr = getCurrentInstance();
    const route = curr?.appContext.config.globalProperties.$route;
    return route;
}

function useRouter(){
    const curr = getCurrentInstance();
    const router = curr?.appContext.config.globalProperties.$router;
    return router;
} */
const route = useRoute();
const router = useRouter();



const RegParams = reactive<RegParamsRaw>({
    tel: "17386141517",
    password: "",
})

const CodeParams = reactive<CodeParams>({
    tel: toRef(RegParams, "tel"), // ref自动解包
    telcode: "",
})

const passwordShow = ref(false);
const regForm = ref();
const isTelOk = ref(false);


let validateTel = function(value:any,rule:any):Promise<any>|boolean|string|void{
    console.log(rule,value);

    return new Promise(function(resolve,reject){
        doCheckPhoneAPI({tel:RegParams.tel}).then((result)=>{
            console.log(result);
            showSuccessToast("可以使用的手机号");
            resolve(true); // 校验成功

            isTelOk.value = true;
        }).catch(()=>{
            resolve(rule.message); //校验失败,返回失败的信息 
        })
    })

}


let validateCode = function(value:any,rule:any):Promise<any>|boolean|string|void{
    console.log(rule,value);

    return new Promise(function(resolve,reject){

        doCheckCodeAPI(CodeParams).then((result)=>{
            console.log(result);
            showSuccessToast("验证码校验成功");
            resolve(true); // 校验成功
        }).catch(()=>{
            resolve(rule.message); //校验失败,返回失败的信息 
        })
    })

}


const LoginRules = reactive<RegRules>({
    tel: [
        { required: true, message: '请填写手机号', trigger: "onChange" },
        { pattern: reg.phone, message: '请填写正确的手机号', trigger: "onChange" },
        {validator:validateTel, message: '手机号已被注册', trigger: "onChange"}
    ],
    password: [
        { required: true, message: '请填写密码', trigger: "onChange" },
        { pattern: reg.pwd, message: '请输入6-16位的数字加字母', trigger: "onChange" },
    ],
    telcode: [
        { required: true, message: '请填写验证码', trigger: "onChange" },
        { validator:validateCode, message: '验证码输入错误', trigger: "onChange" }
    ],
})



const sendCode = ():void=> {
    console.log(regForm.value);

    // 点击发送验证码是,再次校验手机号

    regForm.value.validate("tel").then(()=>{
        console.log("校验成功!!");
        doSendMsgCodeAPI({tel:RegParams.tel}).then((result)=>{
            showSuccessToast("验证码发送成功");
            console.log("验证码发送成功",result);

            CodeParams.telcode = result.data; // 假装收到验证码,输入到输入框
        }).catch(()=>{

        })
    })
    
    

    // if(RegParams.tel){
    //     doSendMsgCodeAPI({tel:RegParams.tel})
    // }else{
    //     showFailToast("请先输入手机号");
    // }
}






const onClickIcon = () => {
    passwordShow.value = !passwordShow.value;
}


const onSubmit = () => {
    console.log(regForm.value.getValidationStatus());
    let obj = regForm.value.getValidationStatus();

    let values = Object.values(obj);
    if(values.every((v)=>v==="passed")){
        console.log("可以注册");
        doFinishRegisterAPI(RegParams).then(()=>{
            // 跳转登录页  

            router.replace("/login");
           
        })
    }else{
    }
    
}
</script>

<style lang="scss" scoped>
.register {
    background-color: #f7f8fa;

    .regForm {
        margin-top: 50px;
    }
}
</style>